package com.zhxl.mvc.Dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;

import com.zhxl.model.Internal.User;
//@Configuration
@Repository
public class QueryContextDaoImpl 
{
		
	//@Resource(name="sessionFactory")//在xml定义sessionFactory属性org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined
	//@Autowired
	//@Qualifier("sessionFactory")
	//public void setSessionFactory(SessionFactory sessionFactory){
		//this.sessionFactory=sessionFactory;
	//}
	@Autowired
	SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}


	@SuppressWarnings("unchecked")
	public List<User> getContext() {
		List<User> users = new ArrayList<User>();
		
		System.out.println(sessionFactory==null);
		if(sessionFactory==null){
			User un = new User();
			un.setAge("123");
			un.setId("222");
			un.setName("sessionFactory is null");
			users.add(un);
			return users;
		}
		Session session = sessionFactory.openSession();
		/**
		 * 使用Session session = getSessionFactory().getCurrentSession();报错Could not obtain transaction-synchronized
		 */
		//could not open connect access denied for user 
		//username or password 错误
		
		Transaction transaction = session.beginTransaction();
		/*
		 * 下面写法报错nested transactions not supportedat org.
		 * 事务嵌套异常
		 */
		//session.beginTransaction().begin();
		//session.beginTransaction().begin();
		User u = null;
		User u2 = null;
		u = (User) session.get(User.class, "12");
		u2 = (User) session.get(User.class, "4028868e4f40ca2b014f40ca2df00000");
		/**
		 * from user其中user一定要与model的entity name值一致
		 */
		
		if(users.size()>0){
			return users;
		}
		String name = u.getName();
		System.out.println(name);
		transaction.commit();
		if(u == null){
			users = session.createQuery("from user").list();
		}
		if(u2!=null){
			users.add(u2);
		}
		users.add(u);
		return users;
	}
}
